package com.pqc.tbk.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

@Repository
public class BaseDaoSupport<T> implements BaseDao<T> {

	@PersistenceContext
	protected EntityManager em;

	@Override
	public void save(final T entity) {
		em.persist(entity);
	}

	@Override
	public void update(final T entity) {
		em.merge(entity);
	}

	@Override
	public void delete(final T entity) {
		em.remove(entity);
	}

	@Override
	public void delete(final Long id, final Class<T> clazz) {
		em.createQuery("delete from " + clazz.getName() + " where id = " + id)
				.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T findOne(final Long id, final Class<T> clazz) {
		return em.find(clazz, id);
	}

	@Override
	public Long count(final Class<T> clazz) {
		Long cnt = 0L;
		cnt = (Long) em.createQuery("select count(*) from " + clazz.getName())
				.getSingleResult();
		return cnt;
	}

	@Override
	public Page<T> getSearchPage(String condition, final Pageable pageable,
			final Class<T> clazz) {
		// 获取查询总条数 此处有待优化
		final String GETCOUNT = "select count(*) from " + clazz.getName()
				+ "  where 1=1 ";
		final long total = (Long) em.createQuery(GETCOUNT + condition)
				.getSingleResult();
		// 拼接查询字符串
		condition = "from " + clazz.getName() + " where 1=1 " + condition;
		// 创建查询
		final TypedQuery<T> query = em.createQuery(condition, clazz);
		// 设置分页
		query.setFirstResult(pageable.getOffset());
		query.setMaxResults(pageable.getPageSize());
		// 构造page对象
		final Page<T> page = new PageImpl<T>(query.getResultList(), pageable,
				total);
		return page;
	}
}
